/*
 * @Author: lbt666 '1319451895@qq.com'
 * @Date: 2022-07-26 14:41:14
 * @LastEditors: lbt666 lbt666@@
 * @LastEditTime: 2023-07-05 22:01:17
 * @Description: 登录，签名，获取token
 * @return {返回值类型} Boolean
 */

import { Dialog } from 'vant';
import { login, addressNonce } from '@/api/request'
import { getToken, removeToken, setToken } from '@/utils/auth'

export async function userAuthorization (store, callback) {
  let sign = localStorage.getItem('signDestry')
  let scaddress = localStorage.getItem('address')
  let token = getToken()
  let nonce = store.nonce

  let userRefuseSign = localStorage.getItem('userRefuseSign') || false
  // 存在签名
  sign = JSON.parse(sign)
  if (sign && (sign.address === scaddress) && token) {
    callback(true)
  } else {
    console.log('store', store)
    if (nonce == null && scaddress) {
      let res = await addressNonce(scaddress || store.address)
      store.SET_Nonce(res.data)
      nonce = res.data
    }
    userSign(callback)
  }
  async function userSign (callback, args) {
    try {
      console.log('clear')
      localStorage.removeItem('sign')
      localStorage.removeItem('signDestry')
      removeToken()
      let signs = await store.WEB3.eth.personal.sign("welcome to BBL, pls sign this message to login! NONCE: " + store.nonce, store.address)
      // console.log('地址签名成功', signs)
      let val = {
        sign: signs,
        address: store.address
      }
      localStorage.setItem('signDestry', JSON.stringify(val))
      await getUserToken(store, signs)
      callback(true)
    } catch (e) {
      callback(false)
      console.log('取消', e, store.address)
      if (store.address && userRefuseSign == false) {
        Dialog.confirm({
          title: '提示',
          confirmButtonColor: '#1F75D9',
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          message: '请先获取签名',
        })
          .then(() => {
            userAuthorization(store, callback)
          })
          .catch(() => {
            // on cancel 用户拒绝签名
            localStorage.setItem('userRefuseSign', true)
            localStorage.removeItem('signDestry')
            removeToken()
          });
      }
    }
  }
  async function getUserToken (store, sign) {
    let data = {
      address: store.address,
      sign: sign
    }
    let res = await login(data)
    if (res.status == 200) {
      setToken(res.data)
      getSaveCode()
    }
  }
}
// 邀请好友
async function getSaveCode () {
  let token = getToken()
  let code = location.search
  if (code.indexOf('code=') > 0 && token) {
    let res = await addressRelParent()
    if (res.data === '') {
      let val = await addressRelInviter(code.split('=')[1])
      console.log(123123, val)
    }
  }
}